/**
 * COPYRIGHT (C) 2009. Denny Tran, Omar Jaime, David Deng, Julie Hsieh. All Rights Reserved
 * Draws an hour view of a calendar.  
 * @author Denny Tran, Omar Jaime, David Deng, Julie Hsieh 
 * @version 1.01 2009-05-05
 */

package gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.imageio.ImageIO;
import javax.swing.*;

import data.Event;
import data.GroupSystem;
import data.MyCalendar;


public class CalendarComponent extends JPanel
{
	private String[] months = { "January", "February", "March", "April", "May", "June", "July", "August",
            "September", "October", "November", "December" };
	private Integer[] days = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
    private Integer[] years = {2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020};
    
    public static int HOUR_SIZE = 50;
    public static int DAY_WIDTH = 85;
    public static int STARTX = 70;
    public static int STARTY = 80;//was 45
    private ArrayList<EventComponent> eventComponents;
    private ViewManager viewManager;    
    private JLabel title;
    private JButton prevWeek;
    private JButton nextWeek;
    private CalendarPanel parent;    
    private String[] dayNum;
    private JScrollPane scrollPane;
    private JPanel timePanel;
    
    /**
     * Constructs an hour view of a calendar.
     * @param viewManager The viewManager to connect to this component.
     * @param cPanel The calendar panel that the component exists in.
     */
    public CalendarComponent(ViewManager viewManager, CalendarPanel cPanel)
    {
        this.viewManager = viewManager;
        this.parent = cPanel;
        eventComponents = new ArrayList<EventComponent>();
        dayNum = new String[8];
        this.setPreferredSize(new Dimension(600,1290));
        this.setBackground(Color.WHITE);
        this.setLocation(0,0);
        this.setLayout(null);  
        
        //title
        title = new JLabel(months[parent.getCurrent().get(Calendar.MONTH)] + " " + parent.getCurrent().get(Calendar.YEAR));
        title.setFont(new Font("Serif", Font.PLAIN, 24));       
        title.setSize(180, 30);
        title.setLocation(300, 5);
        this.add(title);
        setDayNumbers(parent.getCurrent());
        
     // previous month
        //ImageIcon backArrow = new ImageIcon("C:\\Documents and Settings\\Dave\\Desktop\\prev.png");
        //ImageIcon backArrow = new ImageIcon("prev.png");
        URL imageURL = CalendarComponent.class.getResource("prev.png");
        prevWeek = new JButton(new ImageIcon(imageURL));
        prevWeek.addActionListener(new ActionListener()
        {
			public void actionPerformed(ActionEvent e)
			{
				parent.getCurrent().add(Calendar.WEEK_OF_YEAR, -1);
				parent.reload();
				//title.setText(months[parent.getCurrent().get(Calendar.MONTH)]);
			} 	
        });
        prevWeek.setSize(40,40);
        prevWeek.setLocation(5,10);
        prevWeek.setBackground(Color.WHITE);
        prevWeek.setBorderPainted(false);
        this.add(prevWeek);
        
        // next month
        //ImageIcon forwardArrow = new ImageIcon("C:\\Documents and Settings\\Dave\\Desktop\\next.png");
        //ImageIcon forwardArrow = new ImageIcon("next.png");
        imageURL = CalendarComponent.class.getResource("next.png");
        nextWeek = new JButton(new ImageIcon(imageURL));
        nextWeek.addActionListener(new ActionListener()
        {
			public void actionPerformed(ActionEvent e)
			{
				parent.getCurrent().add(Calendar.WEEK_OF_YEAR, 1);
				parent.reload();			
				//title.setText(months[parent.getCurrent().get(Calendar.MONTH)]);
			} 	
        });
        nextWeek.setSize(40,40);
        nextWeek.setLocation(650,10);
        nextWeek.setBackground(Color.WHITE);
        nextWeek.setBorderPainted(false);
        this.add(nextWeek);
        
        timePanel = new JPanel()
        {
            public void paintComponent(Graphics g)
            {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                
                int xCoord = 5;
                int yCoord = 30;
                int ySpread = 50;
                
                //this.setFont(new Font("serif", Font.PLAIN, 12));
                //times
                String ampm = "AM";
                for (int i = 0; i < 2; i++)
                {
                    for (int j = 0; j < 12; j++)
                    {
                        String time = String.format("%2d:00%s", (j+11)%12 + 1, ampm);
                        g2.drawString(time, xCoord, yCoord);
                        yCoord += ySpread;
                    }
                    ampm = "PM";
                }
                g2.drawString("12:00AM", xCoord, yCoord); // the last midnight
                
                // vertical lines
                xCoord = 70;
                yCoord = 30;
                int xSpread = DAY_WIDTH;
                for (int i = 0; i < 8; i++)
                {
                    g2.drawLine(xCoord,yCoord, xCoord,1230); //added 45 to both y params
                    xCoord += xSpread;
                }
                
                // horizontal lines
                xCoord = 70;
                yCoord = 30;
                ySpread = HOUR_SIZE;
                for (int i = 0; i < 25; i++)
                {
                    g2.drawLine(xCoord, yCoord, 665, yCoord);
                    yCoord += ySpread;
                }
            }
        };
        timePanel.setPreferredSize(new Dimension(600,1250));
        timePanel.setBackground(Color.white);
        timePanel.setLayout(null);
        scrollPane = new JScrollPane(timePanel);
        scrollPane.setSize(695, 370);
        scrollPane.setLocation(0,80);
        this.add(scrollPane);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        
        JButton jumpToDateButton = new JButton("Jump to date");
        jumpToDateButton.setSize(130,20);
        jumpToDateButton.setLocation(480,10);
        jumpToDateButton.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent arg0)
            {
               // jump to date
               JPanel datePanel = new JPanel();
               JComboBox startmonthBox = new JComboBox(months);
               startmonthBox.setSize(90, 20);
               JComboBox startdayBox = new JComboBox(days); 
               startdayBox.setSize(50, 20);
               JComboBox startyearBox = new JComboBox(years);
               startyearBox.setSize(60, 20);
               datePanel.add(startmonthBox);
               datePanel.add(startdayBox);
               datePanel.add(startyearBox);

               JOptionPane jumpToDate = new JOptionPane(datePanel, JOptionPane.PLAIN_MESSAGE,
                     JOptionPane.OK_CANCEL_OPTION,
                     null, null);

               JDialog dialog = jumpToDate.createDialog(null, "Login");
               dialog.setVisible(true);

               int result = JOptionPane.OK_OPTION;

               if(result == JOptionPane.OK_OPTION)
               {
                  int year = (Integer) startyearBox.getSelectedItem();
                  int month = startmonthBox.getSelectedIndex();
                  int day = (Integer) startdayBox.getSelectedItem();
                  
                  GregorianCalendar start = new GregorianCalendar(year, month, day);
                  parent.setCurrent(start);
                  parent.reload();
               }
               else
                   System.out.println("Canceled");
               
            }
           
        });
        this.add(jumpToDateButton);
    }
    
    /**
     * Sets the day numbers on top of the days depending on the week.
     * @param cal The date reference for the numbers.
     */
    private void setDayNumbers(GregorianCalendar cal)
    {
    	int currentDay = cal.get(Calendar.DAY_OF_MONTH);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        GregorianCalendar temp1 = (GregorianCalendar) cal.clone();
        GregorianCalendar temp2 = (GregorianCalendar) cal.clone();
        dayNum[dayOfWeek] = currentDay + "";
        for(int i = dayOfWeek - 1; i > 0; i--)
        {
        	temp1.add(Calendar.DAY_OF_YEAR, -1);
        	dayNum[i] = temp1.get(Calendar.DAY_OF_MONTH) + "";
        }
        for(int i = dayOfWeek + 1; i < 8; i++)
        {
        	temp2.add(Calendar.DAY_OF_YEAR, 1);
        	dayNum[i] = temp2.get(Calendar.DAY_OF_MONTH) + "";
        }
    }
    
    /**
     * Creates the event components and places them on the calendar.
     * @param events The list of events to display.
     */
    public void showEvents(ArrayList<Event> events)
    {
        this.clearComponent(); // clear out old events
        for (Event e : events)
        {
            EventComponent ec = new EventComponent(viewManager, e);             
            eventComponents.add(ec);
            timePanel.add(ec);
        }
        title.setText(months[parent.getCurrent().get(Calendar.MONTH)]+ " " + parent.getCurrent().get(Calendar.YEAR));
        setDayNumbers(parent.getCurrent());
        parent.repaint();
    }
    
    /**
     * Used for the "all" calendar showing busy and free times.
     */
    public void showBusy()
    {
        for (EventComponent e : eventComponents)
        {
            // don't display deadlines for "all tab" since they don't have duration
            if (e.getCurrentEvent().getType().equals("deadline"))
                timePanel.remove(e);
            e.setText(""); // clear messages
            e.setBackground(Color.black);
            e.removeMouseListener(e.listener);
            e.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }
    
    /**
     * Clears the calendar of the event components.
     */
    public void clearComponent()
    {
        for (EventComponent e : eventComponents)
            timePanel.remove(e);
        
        eventComponents.clear();
    }
    
    /**
     * Draws the lines and times on the calendar.
     */
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        
        int xCoord = 5;
        int yCoord = 85; //was 50
        int ySpread = 50;
        int xSpread;
        
//        //this.setFont(new Font("serif", Font.PLAIN, 12));
//        //times
//        String ampm = "AM";
//        for (int i = 0; i < 2; i++)
//        {
//            for (int j = 0; j < 12; j++)
//            {
//                String time = String.format("%2d:00%s", (j+11)%12 + 1, ampm);
//                g2.drawString(time, xCoord, yCoord);
//                yCoord += ySpread;
//            }
//            ampm = "PM";
//        }
//        g2.drawString("12:00AM", xCoord, yCoord); // the last midnight
//        
//        // vertical lines
//        xCoord = 70;
//        int xSpread = DAY_WIDTH;
//        for (int i = 0; i < 8; i++)
//        {
//            g2.drawLine(xCoord,80, xCoord,1280); //added 45 to both y params
//            xCoord += xSpread;
//        }
//        
//        // horizontal lines
//        xCoord = 70;
//        yCoord = 80; //originally 45
//        ySpread = HOUR_SIZE;
//        for (int i = 0; i < 25; i++)
//        {
//            g2.drawLine(xCoord, yCoord, 665, yCoord);
//            yCoord += ySpread;
//        }
        
        //sets numbers over day
        //this.setFont(new Font("serif", Font.BOLD, 12));
        xCoord = 100;
        yCoord = 50;// was 40
        xSpread = 85;
        for (int i = 1; i < dayNum.length; i++)
        {
            g2.drawString(dayNum[i], xCoord, yCoord);
            xCoord += xSpread;
        }   
        
        //this.setFont(new Font("serif", Font.PLAIN, 12));
        // Days
        String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        xCoord = 80;
        yCoord = 70;// was 40
        xSpread = 85;
        for (int i = 0; i < days.length; i++)
        {
            g2.drawString(days[i], xCoord, yCoord);
            xCoord += xSpread;
        }       
    }
}
